import 'dart:async';

import 'package:flutter/material.dart';
import "package:get/get.dart";
import 'package:osg/controllers/http.dart';
 import '../../middleware/h5_upimg.dart' if (dart.library.io) '../../middleware/andino_upimg.dart';



 final RxInt idTopic=0.obs;
  RxInt currentCount = 0.obs; // 当前计数器值（虽然在这个示例中不会改变）
 late TextEditingController _controller2;

class Publish extends StatefulWidget {
  @override
  _InputCounterState createState() => _InputCounterState();
}

class _InputCounterState extends State<Publish> {

 late TextEditingController _controller;
 RxList imgList = [].obs;
  final RxInt _selectedValue = 1.obs;

    @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width / 2.3;
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xffffffff),
          centerTitle: true,
          leadingWidth: 40,
          title: Text('发动态'),
          leading: IconButton(
            onPressed: () {
              Get.back();
              print('object');
            },
            icon: Image.asset('static/images/back.png'),
          ),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 20,
              transform: Matrix4.translationValues(0.0, -10.0, 0.0),
              decoration: BoxDecoration(
                  color: Color(0xffffffff),
                  borderRadius: BorderRadius.circular(20)),
            ),
            Container(
              transform: Matrix4.translationValues(0.0, -10.0, 0.0),
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    constraints: BoxConstraints(
                      minHeight: 130, // 设置最小高度
                    ),
                    child: TextField(
                      onChanged: (value) {
                        currentCount.value = value.length;
                      },
                      maxLength: 200,
                      controller: _controller,
                      maxLines: null,
                      decoration: InputDecoration(
                        counterText: '',
                        hintStyle:
                            TextStyle(color: Color(0xff999999), fontSize: 12),
                        border: InputBorder.none, // 移除边框
                        hintText: '记录这一刻的想法...',
                      ),
                    ),
                  ),
                  InputFieldWithCounter(),
                  SizedBox(height: 15),
                   Obx(
                () => Wrap(
                  spacing: 10,
                  runSpacing: 10,
                  children: [
                    for (int i = 0; i < imgList.length; i++)
                      Stack(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(10), // 设置圆角半径
                            child: Image.network(
                              imgList[i],
                              width: 80,
                              height: 80,
                              fit: BoxFit.fill,
                            ),
                          ),
                          Positioned(
                            top: 5.0,
                            right: 5,
                            child: GestureDetector(
                              onTap: () {
                                imgList.removeAt(i);
                              },
                              child: ClipRRect(
                                borderRadius:
                                    BorderRadius.circular(20), // 设置圆角半径
                                child: Image.asset(
                                  width: 20,
                                  height: 20,
                                  'static/guanbi.png',
                                  fit: BoxFit.fill,
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: Color(0xfff5f5f5)),
                      child: IconButton(
                        iconSize: 30,
                        icon: Icon(Icons.add),
                        color: Color(0xff999999),
                        onPressed: () async {
                          // 点击事件处理
                          print(6666);

                          final result = await ImageUploader.uploadImage();
                          Get.back();
                          if (result != null&&result !='') {
                            imgList.add(result);
                          }
                        },
                      ),
                    )
                  ],
                ),
              ),
                ],
              ),
            ),

            Expanded(child: Container()), // 用于推到底部
            Align(
              alignment: Alignment.center,
              child:  GestureDetector(
                onTap: () => {
                   if(_controller.text.isNotEmpty){
                         if(imgList.isNotEmpty){

                          if(idTopic.value>0){
                              Get.find<HTTPS>().postData('/bbs/addArticle', {
                              'topic_id':idTopic.value,
                              'text':_controller.text,
                              'images':imgList.join(','),
                            }).then((res){
                              if(res!=null){
                               Get.find<HTTPS>().showTost('发布成功');

                                 Timer(Duration(seconds: 1), () {
                                   Get.offNamed('/');
                                });
                              }
                            })
                          }else{
                            Get.find<HTTPS>().showTost('选择话题')
                          }
                         }else{
                          Get.find<HTTPS>().showTost('请上传图片')
                        }
                    }else{
                      Get.find<HTTPS>().showTost('请输入想法')
                    }
                  
                },
                child: Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular((40)),
                    gradient: LinearGradient(
                      colors: [
                        Color(0xff2189E7),
                        Color(0xffBF67F8),
                      ], // 定义颜色列表
                      begin: Alignment.topLeft, // 渐变开始的位置
                      end: Alignment.bottomRight, // 渐变结束的位置
                    ),
                  ),
                  width: 280,
                  height: 40,
                  child: Text('发布',
                      style: TextStyle(fontSize: 16, color: Color(0xffffffff))),
                ),
              ),
            ),
            SizedBox(height: 15)
          ],
        ));
  }

@override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

class InputFieldWithCounter extends StatefulWidget {
  @override
  _InputFieldWithCounterState createState() => _InputFieldWithCounterState();
}

class _InputFieldWithCounterState extends State<InputFieldWithCounter> {
  final int maxCount = 200; // 最大计数器值

 final RxString valueTopic=''.obs;
 final RxString newTopic='话题'.obs;
 final RxList listTopic=[].obs;


  @override
  void initState() {
    super.initState();
    _controller2 = TextEditingController();
  }
   getTopic () async {
   return await Get.find<HTTPS>().getData('/bbs/topic', {}).then((res) {
        if (res != null) {
         return listTopic.value=res;
        }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.only(top: 10),
        padding: EdgeInsets.only(bottom: 10),
        decoration: BoxDecoration(
            border: Border(bottom: BorderSide(color: Color(0xffdddddd)))),
        child: Row(
          children: [
            Container(
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 2),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(28),
                    color: Color(0XFFF5F5F5)),
                child: GestureDetector(
                  onTap: () => {
                    getTopic().then((res){
                      
                        valueTopic.value='';
                        _controller2.text='';
                        Get.bottomSheet(
                          isScrollControlled:true,
                            Container(
                              height: 500,
                              padding: EdgeInsets.symmetric(
                                  horizontal: 15, vertical: 15),
                              child: Column(
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Expanded(
                                          child: Container(
                                        decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(35),
                                            color: Color(0XFFF5F5F5)),
                                        child: Row(
                                          children: [
                                            SizedBox(
                                              width: 15,
                                            ),
                                            Icon(Icons.search,
                                                size: 15,
                                                color: Color(0xff999999)),
                                            Expanded(
                                              child: TextField(
                                                onChanged: (value){
                                                    valueTopic.value =value;
                                                },
                                                controller: _controller2,
                                                style: TextStyle(fontSize: 12),
                                                decoration: InputDecoration(
                                                  isCollapsed: true,
                                                  contentPadding:
                                                      EdgeInsets.symmetric(
                                                          vertical: 15),
                                                  hintStyle: TextStyle(
                                                      color: Color(0xff999999)),
                                                  border: InputBorder
                                                      .none, // 隐藏输入框默认边框
                                                  hintText: '填写话题简介', // 提示文本
                                                ),
                                              ),
                                            ),
                                            GestureDetector(
                                              onTap: (){
                                                _controller2.text='';
                                              },
                                              child:  Image.asset('static/guanbi.png',
                                                width: 16,
                                                fit: BoxFit.fitWidth),
                                            )
                                           ,
                                            SizedBox(
                                              width: 15,
                                            ),
                                          ],
                                        ),
                                      )),
                                      TextButton(
                                        onPressed: () {
                                          Get.back(); // 调用关闭弹窗
                                          // 可在此处执行关闭后的回调逻辑
                                        },
                                        child: Image.asset(
                                          'static/close.png',
                                          width: 16,
                                          fit: BoxFit.fitWidth,
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 15,
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      Get.find<HTTPS>().postData(
                                          '/bbs/addTopic', {
                                        'title': _controller2.text
                                      }).then((res) {
                                        if (res != null) {
                                          Get.find<HTTPS>().showTost('添加成功');
                                          Timer(Duration(seconds: 1), () {
                                            getTopic();
                                          });
                                        }
                                      });
                                    },
                                    child: 
                                        Obx(()=>
                                      valueTopic.value.isEmpty?SizedBox():
                                    Row(
                                      children: [
                                        Image.asset(
                                          'static/images/huatichuangjian.png',
                                          width: 11,
                                          fit: BoxFit.fitWidth,
                                        ),
                                        SizedBox(
                                          width: 5,
                                        ),
                                        Text('创建话题 “${valueTopic.value}”',
                                            style: TextStyle(
                                                fontSize: 12,
                                                color: Color(0XFF6A3BD9))),
                                      ],
                                    ),
                                    ),
                                  ),
                                  Expanded(child: 
                                  Obx(()=>
                                   ListView(
                                    children: [
                                       for (int i = 0; i < listTopic.length; i++)
                                        GestureDetector(
                                          onTap: (){
                                            newTopic.value = listTopic[i]['topic_title'];
                                            idTopic.value = listTopic[i]['id'];
                                            Get.back();
                                          },
                                          child: Column(
                                            children: [
                                              SizedBox(
                                                height: 13,
                                              ),
                                              Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.spaceBetween,
                                                children: [
                                                  Text('# ${res[i]['topic_title']}'),
                                                  Text('${res[i]['click']} 浏览'),
                                                ],
                                              ),
                                            ],
                                        ),
                                        )
                                    ],
                                  )
                                    )
                                  )
                                 
                                 
                                   
                                ],
                              ),
                            ),
                            shape: RoundedRectangleBorder(
                              // 圆角设置:ml-citation{ref="7" data="citationList"}
                              borderRadius: BorderRadius.vertical(
                                  top: Radius.circular(10)),
                            ),
                            backgroundColor: Colors.white);
                    })
                   
                  },
                  child:
                  Obx(()=>
                    Text(
                    '# ${newTopic.value}',
                    style: TextStyle(fontSize: 12),
                  )
                  )
                   ,
                )),
            Expanded(
              child: 
              SizedBox(),
              // TextField(
              //   controller: _controller,
              //   decoration: InputDecoration(
              //     hintStyle: TextStyle(color: Color(0xff999999), fontSize: 12),
              //     border: InputBorder.none, // 移除边框
              //     hintText: '',
              //   ),
              // ),
            ),
            SizedBox(width: 8),
            Obx(()=>
            Text(
              '$currentCount/200',
              style: TextStyle(color: Colors.grey),
            ),
            )
            
          ],
        ));
  }

  @override
  void dispose() {
    _controller2.dispose();
    super.dispose();
  }
}
